-- to_max_career
-- Created by chengb Sep/11/2015
-- 成就：将本系所有称号提升至最高等级

local MAX_COUNT = 5;   -- 可学习的称号数量
local COMMON_FEATURE_COUNT = 3; -- 终极称号普通强化项数量

-- 内部函数声明
local whenUpgradeCareer;

-- 注册升级称号的回调
EventMgr.register("game_achievement/to_max_career", event.UPGRADE_CAREER, function(args)
    whenUpgradeCareer(args);
end);

-- 注册升级称号的回调
whenUpgradeCareer = function(args)
    local pet      = args.pet;
    local careerId = args.careerId;
    local level    = args.level;
    
    local careerInfo = CareerM.getCareerInfo(careerId);
    if level ~= careerInfo.max_level and #careerInfo["base_feature"] == 0 then
        -- 未满级且不是终极称号，无需处理
        return;
    end
    
    -- 获取宠物的称号系别
    local myDept = CareerM.getDepartmentList(pet)[1];
    if myDept ~= careerInfo.department then
        -- 不是本系的称号
        return;
    end
    
    local careerData = pet:getCareerData(myDept);
    if #table.keys(careerData) < MAX_COUNT then
        -- 还有称号没学
        return;
    end
    
    -- 判断是否所有本系的称号都已满级
    for _, info in pairs(careerData) do
        careerInfo = CareerM.getCareerInfo(info.career) or {};
        local maxLevel;
        -- 是否终极称号，只有终极称号有base_feature
        if (#careerInfo["base_feature"] > 0) then
            -- 如果是终极称号，分别计算每个强化项的等级，且不考虑神器强化
            for featureId = 1, COMMON_FEATURE_COUNT do
                if not info["feature"][featureId] then
                    return;
                end

                local featureInfo = careerInfo["feature" .. featureId] or {};
                maxLevel = featureInfo["max_level"] or 0;
                if info["feature"][featureId] < maxLevel then
                    return;
                end
            end
        else
            maxLevel = careerInfo["max_level"] or 0;
            if info.level < maxLevel then
                return;
            end
        end
    end
    
    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == GameAchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        return true;
    end

    -- 遍历所有的子规则
    local ids = GameAchievementM.getIdsByRule("to_max_career");
    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            GameAchievementM.tryComplete(id, 1);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = GameAchievementM.query(id);

        local ruleArg  = config["rule_arg"];
        local progress = config["progress"];
        local desc     = config["desc"];

        desc = string.gsub(desc, "{0}", progress);

        return desc;
    end,
};